<?php
/**
 * Created by PhpStorm.
 * Personal: Administrator
 * Date: 2018/7/31
 * Time: 13:40
 */
class RoleApp extends CommonApp {

	public function manageAct(){
		$result = $this->checkLogin();
        $list['data'] = DB('test')->select();
		$this->assign('result',$result);
        $this->assign('list',$list);
		$this->display();
	}

	public function modifyAct(){
        $result = $this->checkLogin();
        $this->assign('result',$result);
		$this->display();
	}

    // public function listAct(){
    //     $list = DB('test')->select();
    //     $this->assign('list',$list);
    //     $this->display();
    // }
    public function searchAct(){
        if(isset($_POST)){
            $keyword = $_POST;
            $uid = $keyword;
            $result['data'] = DB('test')->where("uid = {$_POST}")->select();
            var_dump($result['data']);
            exit();
        }
    }

       //文件验证
    public function fileAct(){
        if(!empty($_FILES)){
            $upload = new Upload();// 实例化上传类
            $upload->maxSize   = 3145728 ;// 设置附件上传大小
            $upload->allowExts = array('xls', 'xlsx');// 设置附件上传类型
            $upload->savePath  = PUB_DIR.'/share/images/download_file/'; // 设置附件上传（子）目录
            // 上传文件
            if(strstr($_FILES['upload']['name'],"-"))
                $this->ajaxReturn(300,'文件名有误，避免特殊字符!');
            if(file_exists('share/images/download_file/'.$_FILES['upload']['name']))
                $this->ajaxReturn(300,'存在相同的文件名!');
            if(!$upload->upload()) {// 上传错误提示错误信息
                $this->ajaxReturn(300,$upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $inf= $upload->getUploadFileInfo();
            }
            $this->ajaxReturn(200,'share/images/download_file/'.$inf['0']['savename'],'','',$inf['0']['name']);
        }else
            $this->ajaxReturn(300,'请选择需要上传的文件！');

    }

	public function readexcelAct(){
		$filePath = $_POST['name'];
	    require_once(COM_DIR."Excel/PHPExcel/IOFactory.php");
    	//默认用excel2007读取excel，若格式不对，则用之前的版本进行读取
    	$PHPReader = new PHPExcel_Reader_Excel2007();
    	if(!$PHPReader->canRead($filePath)){
    	    $PHPReader = new PHPExcel_Reader_Excel5();
    	    if(!$PHPReader->canRead($filePath)){
    	        self::showErr('无法读取Excel文档!');
    	    }
    	}
    	$PHPExcel = $PHPReader->load($filePath);
    	if(!$PHPExcel)
    	    self::showErr('无法读取Excel文档!');
        //获取表格数量
        // $sheetCount = $PHPExcel->getSheetCount();
    	//读取excel文件中的第一个工作表
    	$currentSheet = $PHPExcel->getSheet(0);
    	//取得最大的列号
    	$allColumn = $currentSheet->getHighestColumn();
    	//取得一共有多少行
    	$allRow = $currentSheet->getHighestRow();
    	//5个列标题
    	$title_arr = array(
    	    'uid',
    	    'name',
    	    'college',
    	    'number',
    	    'email',
            'status',
    	);
    	//判断内容格式是否正确(6个标题是否完全匹配)
    	$error = array();
    	//注意，列数索引是从0开始
    	foreach($title_arr as $key=>$value){
    	    $title = $currentSheet->getCellByColumnAndRow($key,2)->getValue();
    	    if(trim($title)!=$value)
    	        $error[] = "Excel文档格式不符合要求，第".($key+2)."列正确的应该是“{$value}”";
    	}
    	if($error)
    	    self::showErr(My::implode('<br>',My::implode('<br>',$error)));
    	$result = array();
    	//从第三行开始输出，因为excel表中第一、二行为列名。
    	//注意，行数索引是从1开始
    	for($currentRow = 3;$currentRow <= $allRow;$currentRow++){
    	    $row = array();
    	    //从第0列开始输出
    	    foreach($title_arr as $kkk=>$vvv){
    	        $val = $currentSheet->getCellByColumnAndRow($kkk,$currentRow)->getValue();
    	        //空行判断(看必填列有没值，这里3是必填列，具体哪一列根据实际情况设置)
    	        // if($kkk == 3 AND $val==''){
	            //     continue 2;
    	        // }
    	        // else if($kkk == 0)
    	        // {
    	        //     if($val=='')
    	        //         $row[] = '';
    	        //     // else
    	        //     //     $row[] = self::getDay($val);//日期格式转换
    	        // }else{
    	            $row[] =  (string) $val;
    	        // }
    	    }
    	    $result[] = $row;
    	}
    	$data = array('uid','name','college','number','email','status');
        function foo(&$v,$k,$data){
            $v = array_combine($data, array_slice($v,0));
        }
        array_walk($result,'foo', $data);
        $this->insert_data($result);
    	//$result数组就是Excel的内容（不含列名）
    	// return $result;
	}

    public function insert_data($result){
        $count_num=count($result);
        $info = array();
        $k=0;
        while ($k<$count_num){
            foreach($result as $k =>$v){
                    $info['uid'] = $v['uid'];
                    $info['name'] = $v['name'];
                    $info['college'] = $v['college'];
                    $info['number'] = $v['number'];
                    $info['email'] = $v['email'];
                    $info['status'] = $v['status'];
                    $ok = DB('test')->clear()->add($info);
                    $k++;
                }
        }
        if($ok>=0){
            setcookie("time",strtotime(date("Y-m-d H:i:s")),null,'/');
            $this->ajaxReturn(200,"数据插入成功！");
        }
        else  $this->ajaxReturn(300,"数据插入失败！");
    }
    
    
    private function showErr($str){
	    $str = str_replace("\n"," ",$str);
	    exit("<script>parent.err('{$str}')</script>");
	}
	
	private function showSuc($str){
	    exit("<script>parent.suc('{$str}')</script>");
	}
    
 //    //日期转换(Excel的日期转成YYYY-MM-DD格式)
	// private function  getDay($val){
	//     $jd = GregorianToJD(1, 1, 1970);
	//     $gregorian = JDToGregorian($jd+intval($val)-25569);
	//     $gregorian = date('Y-m-d',strtotime($gregorian));
	//     return $gregorian;/**显示格式为 “年-月-日” */
	// }





}